package com.zhoux.mvc.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ServletAction
 */
@SuppressWarnings("unchecked")
@WebServlet("/ServletAction")
public class ServletAction extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletAction() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
//	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		request.setCharacterEncoding("utf-8");
//		response.setCharacterEncoding("utf-8");
//		//获取servlet路径
//		String servletPath=request.getServletPath().split("\\.")[0];
//		ServletContext context=request.getServletContext();
//		Map mvcConfig=(Map) context.getAttribute("mvc");
//		XmlBean xmlBean=(XmlBean) mvcConfig.get(servletPath);
//		try {
//			Action action=(Action) (Class.forName(xmlBean.getAction()).newInstance());
//			action.execute(request, response,xmlBean);
//		} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}
//	}
    /**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		//获取servlet路径
		String servletPath=request.getServletPath().split("\\.")[0];
		ServletContext context=request.getServletContext();
		Map<String,String> configMap= (Map<String, String>) context.getAttribute("configMap");
		try {
			Action action=(Action) Class.forName(configMap.get(servletPath)).newInstance();
			action.execute(request, response);
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		super.destroy();
	}

}
